package com.nathan.crm.service;

import com.nathan.base.BaseService;
import com.nathan.crm.dao.CustomerOrderMapper;
import com.nathan.crm.utils.AssertUtil;
import com.nathan.crm.vo.CustomerOrder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class CustomerOrderService extends BaseService<CustomerOrder,Integer> {

    @Resource
    private CustomerOrderMapper customerOrderMapper;

    /**
     * 添加客户订单
     * @param customerOrder
     */
    @Transactional
    public void addCustomerOrder(CustomerOrder customerOrder) {
        /* 1、参数校验 */
        checkCustomerOrderParams(customerOrder);

        /* 2、设置默认值 */
        customerOrder.setSum(customerOrder.getGoodsNum() * customerOrder.getPrice());
        customerOrder.setCreateDate(new Date());
        customerOrder.setUpdateDate(new Date());

        /* 3、执行添加操作 */
        AssertUtil.isTrue(customerOrderMapper.insertSelective(customerOrder) != 1,"添加订单失败！");
    }

    /**
     * 参数校验
     * @param customerOrder
     */
    private void checkCustomerOrderParams(CustomerOrder customerOrder) {
        // 获取订单号
        String orderNo = customerOrder.getOrderNo();
        // 判断订单号非空
        AssertUtil.isTrue(StringUtils.isBlank(orderNo),"订单号不能为空！");
        // 判断订单号惟一
        CustomerOrder co = customerOrderMapper.selectByOrderNo(orderNo);
        AssertUtil.isTrue(co != null,"订单号已存在，请重新输入！");
        // 订单时间非空
        AssertUtil.isTrue(customerOrder.getOrderDate() == null,"请输入订单时间！");
        // 地址非空
        AssertUtil.isTrue(StringUtils.isBlank(customerOrder.getAddress()),"收获地址不能为空！");
        // 状态非空
        AssertUtil.isTrue(customerOrder.getState() == null,"请选择订单状态！");
        // 货物名称非空
        AssertUtil.isTrue(StringUtils.isBlank(customerOrder.getGoodsName()),"请输入货物名称！");
        // 货物数量非空
        AssertUtil.isTrue(customerOrder.getGoodsNum() == null,"请输入货物数量！");
        // 价格非空
        AssertUtil.isTrue(customerOrder.getPrice() == null,"请输入价格！");
    }
}
